//
//  GSD.m
//  MyFirstIOS
//
//  Created by zhang peiliang on 12-1-26.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "MyClass.h"
#import "JSONKit.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>
#define Ddebug @"false"
//--------------------------- release before quit.
MyClass * gGSD = nil;
NSDictionary * gResult = nil;
//--------------------------- end


@implementation MyClass
@synthesize userName;
@synthesize token;
@synthesize validated;
@synthesize personMarkList;
@synthesize scheduleType;
@synthesize scheduleTypeStr;
@synthesize selectDate;
@synthesize touchPoint;
+ (MyClass *) getInstance {
    if (gGSD == nil) {
        gGSD = [[MyClass alloc] init];
        gGSD.scheduleType = EScheduleType_all;
        gGSD.scheduleTypeStr = @"all";
        CFGregorianDate initSelectDate;
        initSelectDate.year = 0;
        gGSD.selectDate = initSelectDate;
    }
    return gGSD;
}

- (void)dealloc{
    self.scheduleTypeStr = nil;
    self.personMarkList=nil;
    [super dealloc];

}
- (NSString*) getStoredName {
    NSUserDefaults * gUD = [NSUserDefaults standardUserDefaults];
    extern BOOL showPersonImage;
    showPersonImage = [[gUD stringForKey:@"showPersonImage"] isEqualToString:@"true"];
    if (self.userName != nil) {
        return self.userName;
    }
//    return @"test";//-----temp    
    return [gUD stringForKey:@"userName"];
}

- (void) getUser {
	if (self.userName != nil && self.token != nil) {
		return;
	}
    //-------- temp start
//        self.userName = @"test";
//        self.token = @"o8jkvbgzh0ro449";
//        return;
//    //-------- temp end
    NSUserDefaults * gUD = [NSUserDefaults standardUserDefaults];
    self.userName = [gUD stringForKey:@"userName"];
    self.token = [gUD stringForKey:@"token"];
}

- (NSString *) requestApi:(NSString *) api :(NSString *) jsonString {
	NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
	[request setURL:[NSURL URLWithString:api]];
	[request setHTTPMethod:@"POST"];
	[request setTimeoutInterval:10];
	[request addValue:@"application/json" forHTTPHeaderField: @"Content-Type"];
	
	NSMutableData *postBody = [NSMutableData data];
	[postBody appendData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
	[request setHTTPBody:postBody];	
	NSHTTPURLResponse* urlResponse = nil;
	NSString *ret;
	@try {
		NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];//&error -> nil
		NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
			//ret = result;
            ret = [NSString stringWithFormat:@"%@", result];
		}
		else {
			ret = @"no_net";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败，请稍后再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
		}
		[result release];
	}
	@catch (NSException * e) {
		if([self checkNet]==NO) {
			ret = @"no_net";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败，请稍后再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
		}
		else {
			ret = @"unkonwn_error";
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败，请稍后再试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [alert release];
		}
	}
	
	
	return ret;
}
/*
 - (BOOL) connectedToNetwork
 {
 // Create zero addy
 struct sockaddr_in zeroAddress;
 bzero(&zeroAddress, sizeof(zeroAddress));
 zeroAddress.sin_len = sizeof(zeroAddress);
 zeroAddress.sin_family = AF_INET;
 
 // Recover reachability flags
 SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);    
 SCNetworkReachabilityFlags flags;
 
 BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
 CFRelease(defaultRouteReachability);
 
 if (!didRetrieveFlags)
 {
 printf("Error. Could not recover network reachability flags\n");
 return NO;
 }
 
 BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
 BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
 return (isReachable && !needsConnection) ? YES : NO;
 }
 */
- (BOOL) checkNet {
	NSURL *api = [NSURL URLWithString:@"http://bbest100.com/api/testNet"];
	NSURLRequest *requester = [NSURLRequest requestWithURL:api cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
	NSHTTPURLResponse *response;
	[NSURLConnection sendSynchronousRequest:requester returningResponse: &response error: nil];
	if (response == nil) {
		return NO;
	}
	else {
		return YES;
	}
}

/*
 NSDictionary * ret = [yourGSDInstance  validatedUser];
 switch([ret objectForKey:@"code"]) {
 case 0: token = [ret objectForKey:@"content"]; break;
 case 1: error = [ret objectForKey:@"error"]; break;
 default: error = [ret objectForKey:@"error"];
 }
 */
- (NSDictionary *) validatedUser {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	if (self.validated == YES) {
		return ret;
	}
	[self getUser];	
	//验证 token 有效性
	if (self.userName != nil && self.token != nil) {
		NSString *api = @"http://bbest100.com/api/checkToken";
		NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys: self.token, @"token", nil];
		NSString *jsonString = [sendData JSONString];
		NSString *rq = [self requestApi: api: jsonString];

		if ([rq isEqualToString:@"no_net"]) {
			[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
			[ret setObject:@"no_net" forKey:@"error"];
		}
		else if ([rq isEqualToString:@"unkonwn_error"]) {
			[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
			[ret setObject:@"unkonwn_error" forKey:@"error"];
		}
		else {
			NSDictionary *rqDict = [rq objectFromJSONString];
            NSString * i2s;
            i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
			if ([i2s intValue] == 0 ||[i2s intValue] == 3) 
            {
                if ([i2s intValue] == 3) 
                {
                    NSDictionary* dict =  [self refreshToken];    
                    NSString* str = [NSString stringWithFormat:@"%@", [dict objectForKey:@"code"]];
                    if ([str intValue]==0) 
                        self.validated = YES;
                }
                else
                    self.validated = YES;
			}
			else {
				[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
				[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
			}
		}
	}
    else {
        [ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
    }
	return ret;
}

/*
 NSDictionary * ret = [yourGSDInstance  generateToken:strUsername];
 switch([ret objectForKey:@"code"]) {
 case 0: token = [ret objectForKey:@"content"]; break;
 case 4: @"user not exists"; break;
 default: error = [ret objectForKey:@"error"];
 }
 */
- (NSDictionary *) generateToken:(NSString *) sName {
	NSString *api = @"http://bbest100.com/api/generateToken";
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"IOS客户端", @"appName",
                              @"4ouky94z6tyk", @"appKey",
                              sName, @"userName",
                              [[UIDevice currentDevice] name], @"device",
                              nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: api: jsonString];
	
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
        NSString * i2s;
        i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] == 0) {
			[ret setObject:[rqDict objectForKey:@"token"] forKey:@"token"];
			self.userName = sName;
			self.token = [rqDict objectForKey:@"token"];

            NSUserDefaults * gUD = [NSUserDefaults standardUserDefaults];
            [gUD setObject:sName forKey:@"userName"];
            [gUD setObject:self.token forKey:@"token"];
            [gUD setObject:@"true" forKey:@"showPersonImage"];
            [gUD synchronize];
            
		}
		else if ([i2s intValue] < 0) {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 NSDictionary * ret = [yourGSDInstance  getSchedule:dsdateFrom:dsdateTo];
 if ([ret objectForKey:@"code"]==0) {
 if ([ret objectForKey:@"size"] > 0) {
 NSDictionary *list = [rqResult objectForKey:@"list"];
 for ((NSString*) key in list)
 for(NSDictionary* dict in [dict objectForKey:key]) {
 NSDate * beginTime = [dict objectForKey:@"begin"];
 NSDate * endTime = [dict objectForKey:@"end"];
 NSString * name = [dict objectForKey:@"name"];
 NSString * personMark = [dict objectForKey:@"personMark"];
 NSString * personShowName = [dict objectForKey:@"personShowName"];
 NSString * refId = [dict objectForKey:@"refId"];	//wangming : The refId is string now, want int ?
 NSString * type = [dict objectForKey:@"type"];
 }
 }
 }
 refer - listGroup
 */
- (NSDictionary *) getSchedule:(NSDate *) fromTime toTime:(NSDate *) toTime {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	NSString * sBegin = [NSString stringWithFormat:@"%d000", (long long int)[fromTime timeIntervalSince1970]];
	NSString * sEnd = [NSString stringWithFormat:@"%d000", (long long int)[toTime timeIntervalSince1970]];
	
	NSString *api = @"http://bbest100.com/api/listTimeObjectByTime";
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              sBegin, @"begin",
                              sEnd, @"end", nil];
	NSString *jsonString = [sendData JSONString];
	
	NSString *rq = [self requestApi: api: jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"size"]];
			[ret setObject:[NSNumber numberWithInt:[i2s intValue]] forKey:@"size"];
			if ([i2s intValue] > 0) {
                NSMutableDictionary *dictList = [NSMutableDictionary dictionary];
                NSDateFormatter * fYmd = [[NSDateFormatter alloc] init];
                [fYmd setDateFormat:@"YYYYMMdd"];
                NSString * sk;
				NSDictionary * item;
				NSArray *arr = [rqResult objectForKey:@"timeObjectList"];
                int i = [i2s intValue];
				for(NSDictionary* dict in arr) {
                    if ([[dict objectForKey:@"begin"] length] != 13 || [[dict objectForKey:@"begin"] length] != 13) {
                        i--;
                        continue;
                    }
					item = [NSDictionary dictionaryWithObjectsAndKeys:
							[NSDate dateWithTimeIntervalSince1970: [[[dict objectForKey:@"begin"] substringToIndex:10] doubleValue]], @"begin",
							[NSDate dateWithTimeIntervalSince1970: [[[dict objectForKey:@"end"] substringToIndex:10] doubleValue]], @"end",
							[dict objectForKey:@"name"], @"name",
							[dict objectForKey:@"personMark"], @"personMark",
							[dict objectForKey:@"personShowName"], @"personShowName",
							[dict objectForKey:@"refId"], @"refId",
							[dict objectForKey:@"type"], @"type",
                            [dict objectForKey:@"given"], @"given",
							nil];
					//[arrList addObject: item];
                    sk = [fYmd stringFromDate:[item objectForKey:@"begin"]];
                    if ([dictList objectForKey:sk]) {
                        [[dictList objectForKey:sk] addObject:item];
                    }
                    else {
                        [dictList setObject:[NSMutableArray arrayWithObjects: item, nil] forKey:sk];
                    }
				}
                [ret setObject:[NSNumber numberWithInt:i] forKey:@"size"];
				[ret setObject:dictList forKey:@"list"];
				[fYmd release];
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 5、根据人物获取日程对象列表 /listTimeObjectByPerson
 */
- (NSDictionary *) getSchedule:(NSString *) withMark {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
    NSLog(@"%@",withMark);
	NSString *api = @"http://bbest100.com/api/listTimeObjectByPerson";
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              withMark, @"personMark", nil];
	NSString *jsonString = [sendData JSONString];
	
	NSString *rq = [self requestApi: api: jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"size"]];
			if ([i2s intValue] > 0) {
				NSMutableArray *arrList = [[NSMutableArray alloc] init];
				NSMutableDictionary * item;
				NSArray *arr = [rqResult objectForKey:@"timeObjectList"];
                int i = [i2s intValue];
				for(NSDictionary* dict in arr) {
                    if ([[dict objectForKey:@"begin"] length] != 13 || [[dict objectForKey:@"begin"] length] != 13) {
                        i--;
                        continue;
                    }
					item = [NSDictionary dictionaryWithObjectsAndKeys:
							[NSDate dateWithTimeIntervalSince1970: [[[dict objectForKey:@"begin"] substringToIndex:10] doubleValue]], @"begin",
							[NSDate dateWithTimeIntervalSince1970: [[[dict objectForKey:@"end"] substringToIndex:10] doubleValue]], @"end",
							[dict objectForKey:@"name"], @"name",
							[dict objectForKey:@"personMark"], @"personMark",
							[dict objectForKey:@"personShowName"], @"personShowName",
							[dict objectForKey:@"refId"], @"refId",
							[dict objectForKey:@"type"], @"type",
                            [dict objectForKey:@"given"], @"given",
							nil];
					[arrList addObject: item];
				}
                [ret setObject:[NSNumber numberWithInt:i] forKey:@"size"];
				[ret setObject:arrList forKey:@"list"];
				[arrList release];
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}


//前台一般不会调用本函数
- (NSDictionary*) getResultMeta {
    if (gResult != nil) {
        return gResult;
    }
    
    NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
    [self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
    
    NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              [NSNumber numberWithInt:0], @"type",
                              [NSNumber numberWithInt:0], @"code", nil];
    NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/listResultMeta": jsonString];
    
    if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			NSArray *arr = [rqDict objectForKey:@"resultMetaList"];
			if (arr && [arr count] > 0) {
				NSMutableDictionary* dictList = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"init", nil];
				for(NSDictionary* dict in arr) {
					if ([dictList objectForKey:[dict objectForKey:@"type"]]) {
                        if ([[dictList objectForKey:[dict objectForKey:@"type"]] objectForKey:[dict objectForKey:@"code"]]) {
                            [[[dictList objectForKey:[dict objectForKey:@"type"]] objectForKey:[dict objectForKey:@"code"]]
                             setObject:[dict objectForKey:@"text"]
                             forKey:[dict objectForKey:@"result"]];
                        }
                        else {
                            [[dictList objectForKey:[dict objectForKey:@"type"]] setObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                                                                            [dict objectForKey:@"text"],
                                                                                            [dict objectForKey:@"result"], nil]
                                                                                    forKey:[dict objectForKey:@"code"]];
                        }
                    }
                    else {
                        [dictList setObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                             [NSMutableDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:@"text"],
                                              [dict objectForKey:@"result"], nil],
                                             [dict objectForKey:@"code"], nil]
                                     forKey:[dict objectForKey:@"type"]];
                    }
				}
                [dictList removeObjectForKey:@"init"];
				[ret setObject:dictList forKey:@"list"];
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
    //gResult = [NSDictionary dictionaryWithDictionary:ret]; //question : why lost it ? the same as direct gResult !
    gResult = [ret mutableCopy];
	return gResult;
}

/*
 获取某 type 的所有结果
 NSDictionary * ret = [yourGSDInstance  getResultMeta:type];
 if (ret != nil) {
 for(NSDictionary* code in ret) {
 for(NSDictionary* result in [ret objectForKey:code]) {
 NSString * txt = [[ret objectForKey:code] objectForKey:result];
 }  
 }
 }
 */
- (NSDictionary*) getResultMeta:(NSString*)type {
    [self getResultMeta];
    if (gResult == nil || [[gResult objectForKey:@"code"] intValue]!=0) {
        return nil;
    }
    NSDictionary* ret = [gResult objectForKey:@"list"];
    return [ret objectForKey:type];
}

/*
 获取某 type 的某一类结果
 NSDictionary * ret = [yourGSDInstance  getResultMeta:type:ofKind];
 if (ret != nil) {
 for(NSDictionary* result in [ret objectForKey:code]) {
 NSString * txt = [ret objectForKey:result];
 }
 }
 */
- (NSDictionary*) getResultMeta:(NSString*)type ofKind:(NSString*)code {
    [self getResultMeta];
    if (gResult == nil || [[gResult objectForKey:@"code"] intValue]!=0) {
        return nil;
    }
    NSDictionary* ret = [[gResult objectForKey:@"list"] objectForKey:type];
    if (ret) {
        return [ret objectForKey:code];
    }
    return nil;
}

/*
 获取某 type 某 code 某 result 的文本
 NSString * ret = [yourGSDInstance  getResultMeta:type:ofKind:ofResult];
 if (ret != nil) {
 NSString * txt = ret;
 }
 */
- (NSString*) getResultText:(NSString*)type ofKind:(NSString*)code ofResult:(NSString*)result {
    [self getResultMeta];
    if (gResult == nil || [[gResult objectForKey:@"code"] intValue]!=0) {
        return nil;
    }
    NSDictionary* ret = [[gResult objectForKey:@"list"] objectForKey:type];
    if (ret && [ret objectForKey:code]) {
        return [[ret objectForKey:code] objectForKey:result];
    }
    return nil;
}


/*
 6、通过ID获取计划 /getPlanById
 NSDictionary * ret = [yourGSDInstance getPlan:byId];
 if ([ret objectForKey:@"code"]==0) {
 NSString * name = [ret objectForKey:@"name"];
 ......
 //NSNumber id 标识ID
 //NSNumber alarm 提醒，-1不提醒，0正点提醒，5提前五分钟
 //NSDate begin 开始时间
 //NSDate end 结束时间
 //String location 地点
 //String memo 私密备注                                      to Tony: 可能没有此属性，要判断 if ([[ret allKeys] containsObject:@"memo"])
 //String name 计划名称
 //String personMark 人物标识                                to Tony: 可能没有此属性，要判断 if ([[ret allKeys] containsObject:@"personMark"])
 //String shareMemo 共享备注
 //String editable 可编辑 "true" || "false"                    to Tony: 前台应根据此处判断“编辑”按钮是否可用
 //String shareToBoss 共享给主管 "true" || "false"
 //String shareToCustomer 共享给客户 "true" || "false"
 //String type 计划类型 (int)
 //String kind 计划完成类型 (int)
 }
 else {
 print [ret objectForKey:@"error"];
 }
 */
- (NSMutableDictionary *) getPlan:(NSString *) byId {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              byId, @"planId", nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/getPlanById": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			[ret setObject:byId forKey:@"id"];
            NSDictionary * d = [rqDict objectForKey:@"plan"];
			[ret setObject:[d objectForKey:@"type"] forKey:@"type"];//NSString,类型
			[ret setObject:[d objectForKey:@"code"] forKey:@"kind"];
            [ret setObject:[d objectForKey:@"name"] forKey:@"name"];
			[ret setObject:[d objectForKey:@"location"] forKey:@"location"];//String,地点
			[ret setObject:[d objectForKey:@"shareMemo"] forKey:@"shareMemo"];//String,备注
			if ( [[d allKeys] containsObject:@"memo"] ) {
                [ret setObject:[d objectForKey:@"memo"] forKey:@"memo"];//String,私密备注
            }
            if ([[d allKeys] containsObject:@"personMark"]) {
                [ret setObject:[d objectForKey:@"personMark"] forKey:@"personMark"];//String,人物标识
            }
            //[ret setObject:[d objectForKey:@"personMark"] forKey:@"personMark"];//String,人物标识
			[ret setObject:[NSNumber numberWithInt:[[d objectForKey:@"alarm"] intValue]] forKey:@"alarm"];//int，是否提醒—— -1：不提醒，0：正点提醒，n:提前n分钟提醒
			[ret setObject:[NSDate dateWithTimeIntervalSince1970: [[[d objectForKey:@"begin"] substringToIndex:10] doubleValue]] forKey:@"begin"];//NSDate，开始时间
			[ret setObject:[NSDate dateWithTimeIntervalSince1970: [[[d objectForKey:@"end"] substringToIndex:10] doubleValue]] forKey:@"end"];//NSDate，结束时间
            [ret setObject:[d objectForKey:@"editable"] forKey:@"editable"];//BOOL,可否编辑 true - YES
			[ret setObject:[d objectForKey:@"shareToBoss"] forKey:@"shareToBoss"];//BOOL,是否共享给主管
			[ret setObject:[d objectForKey:@"shareToCustomer"] forKey:@"shareToCustomer"];//BOOL,是否共享给客户
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 10、通过ID获取记录 /getDeedById
 参见 getPlanById                                     to Tony: 和 plan 一样，前台应根据 editable 属性判断“编辑”按钮是否可用
 */
- (NSDictionary *) getDeed:(NSString *) byId {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              byId, @"deedId", nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/getDeedById": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			[ret setObject:byId forKey:@"id"];
            NSDictionary * d = [rqDict objectForKey:@"deed"];
			[ret setObject:[d objectForKey:@"type"] forKey:@"type"];//NSString,类型
			[ret setObject:[d objectForKey:@"code"] forKey:@"kind"];
			[ret setObject:[d objectForKey:@"name"] forKey:@"name"];
			[ret setObject:[d objectForKey:@"location"] forKey:@"location"];//String,地点
			[ret setObject:[d objectForKey:@"shareMemo"] forKey:@"shareMemo"];//String,备注
			if ( [[d allKeys] containsObject:@"memo"] ) {
                [ret setObject:[d objectForKey:@"memo"] forKey:@"memo"];//String,私密备注
            }
            if ([[d allKeys] containsObject:@"personMark"]) {
                [ret setObject:[d objectForKey:@"personMark"] forKey:@"personMark"];//String,人物标识
            }
			[ret setObject:[NSNumber numberWithInt:[[d objectForKey:@"alarm"] intValue]] forKey:@"alarm"];//int，是否提醒—— -1：不提醒，0：正点提醒，n:提前n分钟提醒
			[ret setObject:[NSDate dateWithTimeIntervalSince1970: [[[d objectForKey:@"begin"] substringToIndex:10] doubleValue]] forKey:@"begin"];//NSDate，开始时间
			[ret setObject:[NSDate dateWithTimeIntervalSince1970: [[[d objectForKey:@"end"] substringToIndex:10] doubleValue]] forKey:@"end"];//NSDate，结束时间
            [ret setObject:[d objectForKey:@"editable"] forKey:@"editable"];//BOOL,可否编辑 true - YES
			[ret setObject:[d objectForKey:@"shareToBoss"] forKey:@"shareToBoss"];//BOOL,是否共享给主管
            
            [ret setObject:[d objectForKey:@"result"] forKey:@"result"];
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}
//------------------------ SEPARATOR LINE -----------------------
/*
 7、获取执行结果的选项 /listResultMeta
 a)请求参数：
 String token 令牌
 int type 计划类型
 int code 计划代码		warning : id ?
 b)返回参数：
 List<ApiResultMeta> resultMetaList 执行结果描述列表
 ApiResultMeta属性：
 int code 计划执行结果代码
 String text 显示文字
 */

/*
 8、编辑计划 /editPlan 
 9、完成计划 /finishPlan 与 editPlay 一样，应提供单独接口
 11、编辑记录 /editDeed,应稍加改动
 */
- (NSDictionary *) editPlan:(NSDictionary *) content {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
    
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithDictionary:content];
	
    [sendData setObject:[NSString stringWithFormat:@"%ld000", (long long int)[[sendData objectForKey:@"begin"] timeIntervalSince1970]] forKey:@"begin"];
    [sendData setObject:[NSString stringWithFormat:@"%ld000", (long long int)[[sendData objectForKey:@"end"] timeIntervalSince1970]] forKey:@"end"];
    [sendData setObject:[sendData objectForKey:@"kind"] forKey:@"code"];
    [sendData removeObjectForKey:@"kind"];
    //return sendData;
    sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:sendData, @"plan", nil];
    [sendData setObject:self.token forKey:@"token"];
    
	NSString * jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/editPlan": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] != 0) {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}


/**/
- (NSDictionary *) finishPlan:(NSDictionary *) content {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
    
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithDictionary:content];
	
    [sendData setObject:[NSString stringWithFormat:@"%ld000", (long long int)[[sendData objectForKey:@"begin"] timeIntervalSince1970]] forKey:@"begin"];
    [sendData setObject:[NSString stringWithFormat:@"%ld000", (long long int)[[sendData objectForKey:@"end"] timeIntervalSince1970]] forKey:@"end"];
    
    sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:sendData, @"plan", nil];
    [sendData setObject:self.token forKey:@"token"];
    if ([[sendData objectForKey:@"plan"] objectForKey:@"result"]) {
        [sendData setObject:[[sendData objectForKey:@"plan"] objectForKey:@"result"] forKey:@"result"];
        [[sendData objectForKey:@"plan"] removeObjectForKey:@"result"];
    }
    else {
        [sendData setObject:@"0" forKey:@"result"];//默认 0
    }
    
	NSString * jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/finishPlan": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] != 0) {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 编辑记录
 */
- (NSDictionary *) editDeed:(NSDictionary *) content {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
    
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithDictionary:content];
	
    [sendData setObject:[NSString stringWithFormat:@"%ld000", (long long int)[[sendData objectForKey:@"begin"] timeIntervalSince1970]] forKey:@"begin"];
    [sendData setObject:[NSString stringWithFormat:@"%ld000", (long long int)[[sendData objectForKey:@"end"] timeIntervalSince1970]] forKey:@"end"];
    
    sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:sendData, @"deed", nil];
    [sendData setObject:self.token forKey:@"token"];
    
	NSString * jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/editDeed": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] != 0) {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 12、列出组别 /listGroup
 MyClass *gs = [MyClass getInstance];
 NSDictionary * ret = [gs listGroup];
 if ([[ret objectForKey:@"code"] intValue]==0) {
 NSArray * arr = [ret objectForKey:@"list"];
 for(NSDictionary * obj in arr) {
 [obj objectForKey:@"name"];
 [obj objectForKey:@"type"]; //int type 组类型，1-客户，2-团队，3-社区
 }
 }
 */
- (NSDictionary *) listGroup {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys: self.token, @"token", nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/listGroup": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			NSArray *arr = [rqResult objectForKey:@"groupList"];
			if (arr && [arr count] > 0) {
				NSMutableArray *arrList = [[NSMutableArray alloc] init];
				NSDictionary * item;
				for(NSDictionary* dict in arr) {
					item = [NSDictionary dictionaryWithObjectsAndKeys:
							[dict objectForKey:@"name"], @"name",
							[dict objectForKey:@"type"], @"type",//string -> int ?
							nil];
					[arrList addObject: item];
				}
				[ret setObject:arrList forKey:@"list"];
				[arrList release];
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([[NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]] intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}


/*
 13、列出人物 /listPerson
 MyClass *gs = [MyClass getInstance];
 NSDictionary * ret = [gs getMembers: nil ofType:nil inOrder:1 startAt:0 limit:10 searchWith:@"郭"];
 if ([[ret objectForKey:@"total"] intValue] > 0) {
 NSArray * arr = [ret objectForKey:@"list"];
 for(NSDictionary * obj in arr) {
 [obj objectForKey:@"personMark"];
 [obj objectForKey:@"personShowName"];
 }
 }
 */
- (NSDictionary *) getMembers: (NSString *) ofGroup ofType:(NSString *) ofType inOrder:(int) inOrder startAt:(int) startAt limit:(int) limit searchWith:(NSString *) searchWith {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     self.token, @"token",
                                     [NSString stringWithFormat:@"%d", inOrder], @"order",
                                     [NSString stringWithFormat:@"%d", startAt], @"skip",
                                     [NSString stringWithFormat:@"%d", limit], @"max",
                                     nil];
	if (ofGroup != nil && ofType != nil) {
		[sendData setObject:[NSDictionary dictionaryWithObjectsAndKeys:ofGroup, @"name", ofType, @"type", nil] forKey:@"group"];
	}
	if (searchWith) {
		[sendData setObject:searchWith forKey:@"keyword"];
	}
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/listPerson": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"total"]];
			[ret setObject:[NSNumber numberWithInt:[i2s intValue]] forKey:@"total"];
			if ([i2s intValue] > 0) {
				NSMutableArray *arrList = [[NSMutableArray alloc] init];
				NSMutableDictionary * item;
				NSArray *arr = [rqResult objectForKey:@"personList"];
				for(NSDictionary* dict in arr) {
					item = [NSMutableDictionary dictionaryWithObjectsAndKeys:
							[dict objectForKey:@"mark"], @"personMark",
							[dict objectForKey:@"showName"], @"personShowName",@"false",@"check",
							nil];
					[arrList addObject: item];
				}
				[ret setObject:arrList forKey:@"list"];
				[arrList release];
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([[NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]] intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 14、获取人物头像 /getPersonImage
 MyClass *gs = [MyClass getInstance];
 NSDictionary * ret = [gs getPersonImage:[NSArray arrayWithObjects:@"/f0", @"2/h", nil]];
 if ([[ret objectForKey:@"code"] intValue] > 0) {
 pic_of_someone = [ret objectForKey:mark_name_of_someone];
 }
 */
- (NSDictionary *) getPersonImage: (NSArray *) withMarks {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     self.token, @"token",
                                     withMarks, @"personMarkList", nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/getPersonImage": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
        //return rqDict;
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] == 0) {
			if ([withMarks count] == [[rqDict objectForKey:@"base64ImageList"] count]) {
				[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
				int i = 0;
				for (NSString * img in [rqDict objectForKey:@"base64ImageList"]) {
                    [ret setObject:[NSData dataWithBase64EncodedString:img] forKey:[withMarks objectAtIndex:i++]];
					//[ret setObject:[MyClass decodeBase64String: img] forKey:[withMarks objectAtIndex:i++]];
                    //[ret setObject:img forKey:[withMarks objectAtIndex:i++]];
				}
			}
			else {
				[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
				[ret setObject:@"unkonwn_error" forKey:@"error"];			//个数不匹配
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 15、列出未读消息 /listUnreadNote
 MyClass *gs = [MyClass getInstance];
 NSDictionary * ret = [gs getNewMessages:0 limit:10];
 if ([[ret objectForKey:@"total"] intValue] > 0) {
 NSArray * arr = [ret objectForKey:@"list"];
 for(NSDictionary * obj in arr) {
 [obj objectForKey:@"personMark"];
 [obj objectForKey:@"personShowName"];
 [dict objectForKey:@"id"];//string
 [dict objectForKey:@"content"];
 [dict objectForKey:@"read"];//string true || false
 [dict objectForKey:@"sent"];//string true || false
 [dict objectForKey:@"special"];string true || false
 [dict objectForKey:@"time"];//NSDate
 }
 }
 */
- (NSDictionary *) getNewMessages: (int) startAt limit:(int) limit {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              [NSString stringWithFormat:@"%d", startAt], @"skip",
                              [NSString stringWithFormat:@"%d", limit], @"max",
                              nil];
	
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/listUnreadNote": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"total"]];
			[ret setObject:[NSNumber numberWithInt:[i2s intValue]] forKey:@"total"];
			if ([i2s intValue] > 0) {
				NSMutableArray *arrList = [[NSMutableArray alloc] init];
				NSDictionary * item;
				NSArray *arr = [rqResult objectForKey:@"noteList"];
				for(NSDictionary* dict in arr) {
					item = [NSDictionary dictionaryWithObjectsAndKeys:
							[dict objectForKey:@"id"], @"id",
							[dict objectForKey:@"content"], @"content",
							[dict objectForKey:@"personMark"], @"personMark",
							[dict objectForKey:@"personShowName"], @"personShowName",
							[dict objectForKey:@"read"], @"read",
							[dict objectForKey:@"sent"], @"isSent",
							[dict objectForKey:@"special"], @"special",
							[NSDate dateWithTimeIntervalSince1970: [[[dict objectForKey:@"time"] substringToIndex:10] doubleValue]], @"time",
							nil];
					[arrList addObject: item];
				}
				[ret setObject:arrList forKey:@"list"];
				[arrList release];
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([[NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]] intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 16、根据人物列出消息 /listNoteByPerson
 参见 (NSDictionary *) getNewMessages: (int) startAt limit:(int) limit
 */
- (NSDictionary *) getNewMessages: (NSString *) withMark startAt:(int) startAt limit:(int) limit {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              withMark, @"personMark",
                              [NSString stringWithFormat:@"%d", startAt], @"skip",
                              [NSString stringWithFormat:@"%d", limit], @"max",
                              nil];
	
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/listNoteByPerson": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue]==0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
			i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"total"]];
			[ret setObject:[NSNumber numberWithInt:[i2s intValue]] forKey:@"total"];
			if ([i2s intValue] > 0) {
				NSMutableArray *arrList = [[NSMutableArray alloc] init];
				NSMutableDictionary * item;
				NSArray *arr = [rqResult objectForKey:@"noteList"];
				for(NSDictionary* dict in arr) {
					item = [NSMutableDictionary dictionaryWithObjectsAndKeys:
							[dict objectForKey:@"id"], @"id",
							[dict objectForKey:@"content"], @"content",
							[dict objectForKey:@"personMark"], @"personMark",
							[dict objectForKey:@"personShowName"], @"personShowName",
							[dict objectForKey:@"read"], @"read",
							[dict objectForKey:@"sent"], @"isSent",
							[dict objectForKey:@"special"], @"special",
							[NSDate dateWithTimeIntervalSince1970: [[[dict objectForKey:@"time"] substringToIndex:10] doubleValue]], @"time",
							nil];
                    [arrList insertObject:item atIndex:0];
					//[arrList addObject: item];
				}
				[ret setObject:arrList forKey:@"list"];
				[arrList release];
			}
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([[NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]] intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}


/*
 17、标记消息为已读 /markNoteRead
 传入的消息 ID 为数组，每个 ID 可以是 @"357", 或 NSNumber
 */
- (NSDictionary *) markMessagesRead: (NSArray *) arrIds {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     self.token, @"token",
                                     arrIds, @"noteIdList", nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/markNoteRead": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] == 0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 18、删除消息 /deleteNote
 */
- (NSDictionary *) delMessages: (NSArray *) arrIds {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     self.token, @"token",
                                     arrIds, @"noteIdList", nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/deleteNote": jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] == 0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 19、发送消息 /sendNote
 warning
 */
- (NSDictionary *) sendMessage: (NSString *) message _to:(NSArray *) _to {
    NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	NSMutableDictionary *sendData = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                     self.token, @"token",
                                     message, @"content",
                                     _to, @"personMarkList", nil];
	NSString *jsonString = [sendData JSONString];
	NSString *rq = [self requestApi: @"http://bbest100.com/api/sendNote": jsonString];
	[ret setObject:jsonString forKey:@"json"];
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqDict = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqDict objectForKey:@"code"]];
		if ([i2s intValue] == 0) {
			[ret setObject:[NSNumber numberWithInt:0] forKey:@"code"];
		}
		else {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqDict objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

/*
 20. 设置APNS设备令牌 /setApnsDeviceToken
 */
- (NSDictionary *) sendApnsToken: (NSString *) apnsToken {
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSString *api = @"http://bbest100.com/api/setApnsDeviceToken";
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",
                              apnsToken, @"apnsDeviceToken",Ddebug,@"debug" ,nil];
	NSString *jsonString = [sendData JSONString];
	
	NSString *rq = [self requestApi: api: jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue] != 0) {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

- (NSDictionary *) refreshToken
{
	NSMutableDictionary *ret = [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:0], @"code", nil];
	[self getUser];
	if (self.token == nil) {
		[ret setObject:[NSNumber numberWithInt:-3] forKey:@"code"];
		[ret setObject:@"no_user" forKey:@"error"];
		return ret;
	}
	
	NSString *api = @"http://bbest100.com/api/refreshToken";
	NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.token, @"token",nil];
	NSString *jsonString = [sendData JSONString];
	
	NSString *rq = [self requestApi: api: jsonString];
	
	if ([rq isEqualToString:@"no_net"]) {
		[ret setObject:[NSNumber numberWithInt:-1] forKey:@"code"];
		[ret setObject:@"no_net" forKey:@"error"];
	}
	else if ([rq isEqualToString:@"unkonwn_error"]) 
    {
		[ret setObject:[NSNumber numberWithInt:-2] forKey:@"code"];
		[ret setObject:@"unkonwn_error" forKey:@"error"];
	}
	else {
		NSDictionary *rqResult = [rq objectFromJSONString];
		NSString * i2s;
		i2s = [NSString stringWithFormat:@"%@", [rqResult objectForKey:@"code"]];
		if ([i2s intValue] == 0) {
            NSString* strToken = [rqResult objectForKey:@"token"];
            if (strToken)
            {		
                self.token = strToken;
                NSUserDefaults * gUD = [NSUserDefaults standardUserDefaults];
                [gUD setObject:strToken forKey:@"token"];
                [gUD synchronize];
                [ret setObject: strToken forKey:@"token"];
            }
		}
        if ([i2s intValue] != 0) {
			[ret setObject:[NSNumber numberWithInt:abs([i2s intValue])] forKey:@"code"];
			[ret setObject:[rqResult objectForKey:@"message"] forKey:@"error"];
		}
	}
	return ret;
}

@end